<template>
  <div v-if="showButton">
    <el-button type="primary" :loading="printLoading" @click="showDialog">{{ $t('order.printLogistics') }}</el-button>

    <el-dialog
      :title="$t('选择物流商')"
      :visible.sync="dialog"
      width="500px"
      style="text-align: left;"
    >
      <template>
        <el-radio
          v-for="(item, index) in integratedLogisticsSettingData"
          :key="index"
          v-model="getDefaultLogisticsType"
          :label="item.logistics_type"
        >
          {{ item.logistics_type }}
        </el-radio>
      </template>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog = false">{{$t('common.cancel')}}</el-button>
        <el-button type="primary" @click="printShipping(getDefaultLogisticsType)" :loading="loading">{{ $t('common.confirm') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {printShippingV2} from "@/api/order";

export default {
  name: 'IntegratedLogisticsButton',
  props:{
    order: {
      type: Object,
    },
    integratedLogisticsSettingData: {
      type: Array,
    },
    defaultLogisticsType: {
      type: String,
    },
  },
  computed: {
    showButton(){
      if (this.integratedLogisticsSettingData.length <= 0) {
        return false
      }
      if (this.order.orderStatus === 1 && this.order.isSpecial === true && !this.order.shipping && this.order.receivingInformationData.id) {
        return true
      }
      if (this.order.accountTypeNum === 1) {
        let flag = (this.order.orderStatus === 1 || this.order.orderStatus === 6) && this.order.shipping && this.order.shipping.logisticMode === 'custom' && this.order.shipping.status === 'pending'
        flag = flag && this.order.ignore === 0
        // 加入地址是否齐全判断，未齐全时需要检测是否有补全的地址
        flag = (flag && this.order.shipping.addressIsComplete) || (flag && (!this.order.shipping.addressIsComplete && this.order.receivingInformationData.id))
        return flag
      }
      if (this.order.accountTypeNum === 4) {
        let flag = (this.order.orderStatus === 1 || this.order.orderStatus === 6) && this.order.shipping && this.order.shipping.shippingId && this.order.performanceType === 2
        flag = flag && this.order.ignore === 0
        return flag
      }
      if (this.order.accountTypeNum === 6) {
        let flag = (this.order.orderStatus === 1 || this.order.orderStatus === 6) && this.order.shipping && this.order.shipping_type === 'SELLER'
        flag = flag && this.order.ignore === 0
        return flag
      }
      // 小包订单
      if (this.order.accountTypeNum === 7 && (this.order.orderStatus === 1 || this.order.orderStatus === 6)) {
        return true
      }
      return false
    }
  },
  data(){
    return {
      dialog: false,
      loading: false,
      printLoading: false,
      getDefaultLogisticsType: ''
    }
  },
  created() {
    this.getDefaultLogisticsType = this.defaultLogisticsType
  },
  methods: {
    showDialog(){
      this.getDefaultLogisticsType = this.defaultLogisticsType
      if (this.integratedLogisticsSettingData.length <= 0) {
        return false
      } else if (this.integratedLogisticsSettingData.length === 1) {
        this.printShipping()
      } else {
        this.dialog = true
      }
    },
    // 打印面单
    printShipping(logisticsType = ''){
      this.loading = true;
      this.printLoading = true;
      printShippingV2(this.order.orderId,{
        accountTypeNum: this.order.accountTypeNum,
        logisticsType: logisticsType,
      })
        .then(res=>{
          this.loading = false;
          this.printLoading = false;
          console.log(res)
          if(res.headers['content-type'].match(/application\/pdf/) && res.status === 200){
            this.loading = false;
            this.printLoading = false;
            const pdfFile = window.URL.createObjectURL(
              new Blob([res.data], { type: "application/pdf" })
            );
            // 跳转页面预览
            window.open(pdfFile);
            // 60秒后释放
            setTimeout(()=>{
              URL.revokeObjectURL(pdfFile); //释放URL对象
            },60000)

            this.$emit('changeOrder',true)
          }else{
            if (res.headers['content-type'].match(/application\/json/)){

              // 创建一个FileReader对象
              const reader = new FileReader();

              // 定义一个回调函数，处理读取完成后的操作
              reader.onload = (event) => {
                // event.target.result 包含了Blob对象的内容作为字符串
                let blobAsText = event.target.result;

                // 在这里，你可以处理blobAsText，比如将其显示在页面上或执行其他操作
                const data = JSON.parse(blobAsText);
                console.log(data)
                if(data.error === 210){
                  this.$message({
                    showClose: true,
                    message: data.message,
                    type: 'error',
                    duration: 6000,
                  });
                }else{
                  this.$errorMessage(data.message);
                  this.$emit('changeOrder',true)
                  return false;
                }
              };

              // 开始读取Blob对象并以文本形式返回

              reader.readAsText(res.data);
            }else{
              this.$errorMessage('服务繁忙请稍后再试');
              return false;
            }
          }
        })
    },
  },

}

</script>

<style scoped lang="scss">

</style>
